#!/usr/bin/env node

/**
 * 强制清理系统代理脚本
 * 这是最后的手段，用于在所有其他方法都失败时强制清理系统代理
 * 
 * 使用方法：
 * node force-cleanup-proxy.js
 * 
 * 或者在PowerShell中：
 * npm run force-cleanup
 */

import { exec } from 'child_process';
import { promisify } from 'util';
import os from 'os';

const execAsync = promisify(exec);
const platform = os.platform();

console.log("🚨 强制系统代理清理工具");
console.log("========================\n");

async function forceCleanupProxy() {
  try {
    console.log(`🔍 检测到操作系统: ${platform}`);
    
    if (platform === 'win32') {
      await forceCleanupWindowsProxy();
    } else if (platform === 'darwin') {
      await forceCleanupMacOSProxy();
    } else {
      console.log("⚠️ 不支持的操作系统");
      process.exit(1);
    }
    
    console.log("\n✅ 强制清理完成！");
    console.log("🌐 请检查您的网络连接是否恢复正常");
    
  } catch (error) {
    console.error("❌ 强制清理失败:", error.message);
    printManualInstructions();
    process.exit(1);
  }
}

async function forceCleanupWindowsProxy() {
  console.log("🔧 正在强制清理Windows代理设置...");
  
  const commands = [
    // 禁用代理
    'reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyEnable /t REG_DWORD /d 0 /f',
    
    // 清除代理服务器设置
    'reg delete "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyServer /f',
    
    // 重置代理覆盖设置
    'reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyOverride /t REG_SZ /d "localhost;localhost:*;127.*;127.0.0.1:*;*.localhost;::1;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;<local>" /f',
    
    // 重置WinHTTP代理
    'netsh winhttp reset proxy',
    
    // 清理DNS缓存
    'ipconfig /flushdns',
    
    // 清理ARP缓存
    'arp -d *',
    
    // 清理NetBIOS缓存
    'nbtstat -R',
    'nbtstat -RR'
  ];
  
  for (const command of commands) {
    try {
      console.log(`🔧 执行: ${command}`);
      await execAsync(command, { timeout: 10000 });
      console.log(`✅ 成功: ${command}`);
    } catch (error) {
      console.warn(`⚠️ 失败: ${command} - ${error.message}`);
      // 继续执行其他命令
    }
  }
  
  // 强制刷新代理设置
  await forceRefreshWindowsProxy();
}

async function forceRefreshWindowsProxy() {
  console.log("🔄 强制刷新Windows代理设置...");
  
  const refreshScript = `
$code = @"
using System;
using System.Runtime.InteropServices;
public class WinAPI {
    [DllImport("wininet.dll")]
    public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
}
"@

try {
    Add-Type -TypeDefinition $code
    [WinAPI]::InternetSetOption([IntPtr]::Zero, 39, [IntPtr]::Zero, 0) | Out-Null
    [WinAPI]::InternetSetOption([IntPtr]::Zero, 37, [IntPtr]::Zero, 0) | Out-Null
    Write-Host "✅ 代理设置刷新成功"
} catch {
    Write-Host "⚠️ 代理设置刷新失败: $_"
}
  `.trim();
  
  try {
    await execAsync(`powershell -Command "${refreshScript}"`, { timeout: 10000 });
    console.log("✅ 代理设置刷新完成");
  } catch (error) {
    console.warn("⚠️ 代理设置刷新失败:", error.message);
  }
}

async function forceCleanupMacOSProxy() {
  console.log("🔧 正在强制清理macOS代理设置...");
  
  try {
    // 获取所有网络服务
    const { stdout } = await execAsync('networksetup -listallnetworkservices', { timeout: 10000 });
    const services = stdout.split('\n')
      .filter(line => line.trim() && !line.startsWith('*'))
      .slice(1);
    
    for (const service of services) {
      const serviceName = service.trim();
      if (!serviceName) continue;
      
      try {
        console.log(`🔧 清理服务: ${serviceName}`);
        
        // 禁用HTTP代理
        await execAsync(`networksetup -setwebproxystate "${serviceName}" off`, { timeout: 5000 });
        
        // 禁用HTTPS代理
        await execAsync(`networksetup -setsecurewebproxystate "${serviceName}" off`, { timeout: 5000 });
        
        // 禁用SOCKS代理
        await execAsync(`networksetup -setsocksfirewallproxystate "${serviceName}" off`, { timeout: 5000 });
        
        console.log(`✅ 清理完成: ${serviceName}`);
      } catch (error) {
        console.warn(`⚠️ 清理失败: ${serviceName} - ${error.message}`);
      }
    }
    
    // 清理DNS缓存
    try {
      await execAsync('sudo dscacheutil -flushcache', { timeout: 5000 });
      console.log("✅ DNS缓存已清理");
    } catch (error) {
      console.warn("⚠️ DNS缓存清理失败:", error.message);
    }
    
  } catch (error) {
    console.error("❌ macOS代理清理失败:", error.message);
    throw error;
  }
}

function printManualInstructions() {
  console.log("\n🔧 手动清理指南:");
  
  if (platform === 'win32') {
    console.log("\nWindows用户:");
    console.log("1. 按 Win+R 打开运行对话框");
    console.log("2. 输入 inetcpl.cpl 并回车");
    console.log("3. 点击「连接」标签页");
    console.log("4. 点击「局域网设置」");
    console.log("5. 取消选中「为LAN使用代理服务器」");
    console.log("6. 点击「确定」保存设置");
    console.log("\n或者运行以下命令:");
    console.log('reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v ProxyEnable /t REG_DWORD /d 0 /f');
    
  } else if (platform === 'darwin') {
    console.log("\nmacOS用户:");
    console.log("1. 打开「系统偏好设置」");
    console.log("2. 点击「网络」");
    console.log("3. 选择您的网络连接（Wi-Fi或以太网）");
    console.log("4. 点击「高级」按钮");
    console.log("5. 点击「代理」标签页");
    console.log("6. 取消选中所有代理选项");
    console.log("7. 点击「好」保存设置");
  }
}

// 添加进程退出处理
process.on("SIGINT", () => {
  console.log("\n👋 强制清理工具已退出");
  process.exit(0);
});

process.on("uncaughtException", (error) => {
  console.error("\n❌ 发生未预期的错误:", error.message);
  printManualInstructions();
  process.exit(1);
});

// 运行强制清理
forceCleanupProxy(); 